import math
from django.shortcuts import render
from django.http import HttpResponse, Http404
from django.shortcuts import redirect
# Create your views here.
from django.contrib.auth.models import *
import random
import json
from django.contrib.auth.hashers import make_password, check_password

from dictionary_database.models import xhzd_surnfu
from learning_test.models import testResult_surnfu

def auth(func):
    def inner(reqeust,*args,**kwargs):
        v = reqeust.session.get('username','')
        if not v:
            return redirect('/user/login')
        return func(reqeust, *args,**kwargs)
    return inner

def user(request):
    return HttpResponse("heel")

def postUser(request):
    if request.method == "POST":
        email = request.POST.get('mailBox')
        userName = request.POST.get('userName')
        password = request.POST.get('password')
        pswd = make_password(password, None, 'pbkdf2_sha256')
        b2 = User(email=email, username=userName, password=pswd)
        b2.save()
        response = {'flag': True}
        return HttpResponse(json.dumps(response))
    else:
        response = {'flag': False}
        return HttpResponse(json.dumps(response))
        #testResult_surnfu


def selectUser(request):
    if request.method == "POST":
        userName = request.POST.get('userName')
        #print("userName" + userName)
        num = User.objects.filter(username=userName).count()
        response = {'flag': True,'num': num}
        return HttpResponse(json.dumps(response))
    else:
        response = {'flag': False}
        return HttpResponse(json.dumps(response))

def postData(request):
    if request.method == "POST":
        import datetime
        import time
        creater = User.objects.get(username=request.POST.get('name'))
        print("name：" + request.POST.get('name'))
        testType = request.POST.get('testType')

        beginTime = request.POST.get('begintimestamp')
        endTime = request.POST.get('endtimestamp')
        result = request.POST.get('result')
        b2 = testResult_surnfu(creater=creater, testType=testType, beginTime=str(beginTime), endTime=endTime, result=result)
        b2.save()
        response = {'flag': True}
        return HttpResponse(json.dumps(response))
    else:
        response = {'flag': False}
        return HttpResponse(json.dumps(response))
        #testResult_surnfu

@auth
def learningLibrary(request):
    try:
        p = xhzd_surnfu.objects.order_by('id')[:100]
    except xhzd_surnfu.DoesNotExist:
        raise Http404("Poll does not exist")
    return render(request,'learningLibrary.html',{'zd':p})

@auth
def testLibrary(request):
    try:
        num = random.randint(1, 100)
        p = xhzd_surnfu.objects.filter(bihua__lt="10").order_by('id')[num:num + 10]
        for p1 in p:
            sjs = random.randint(1, 100)
            p1.cw = xhzd_surnfu.objects.filter(bihua__lt="10").exclude(py=p1.py).order_by('id')[sjs:sjs + 4]
            sjzq = random.randint(1, 4)
            p1.zq = sjzq
    except xhzd_surnfu.DoesNotExist:
        raise Http404("Poll does not exist")
    return render(request, 'testLibrary.html', {'zd': p})

@auth
def testHighLibrary(request):
    try:
        num = random.randint(1, 100)
        p = xhzd_surnfu.objects.filter(bihua__gte="20").order_by('id')[num:num + 10]
        for p1 in p:
            sjs = random.randint(1, 100)
            p1.cw = xhzd_surnfu.objects.filter(bihua__gte="20").exclude(py=p1.py).order_by('id')[sjs:sjs + 4]
            sjzq = random.randint(1, 4)
            p1.zq = sjzq
    except xhzd_surnfu.DoesNotExist:
        raise Http404("Poll does not exist")
    return render(request,'testHighLibrary.html', {'zd': p})

@auth
def testMiddleLibrary(request):
    try:
        num = random.randint(1, 100)
        p = xhzd_surnfu.objects.filter(bihua__gte="10").filter(bihua__lt="20").order_by('id')[num:num + 10]
        for p1 in p:
            sjs = random.randint(1, 100)
            p1.cw = xhzd_surnfu.objects.filter(bihua__gte="10").filter(bihua__lt="20").exclude(py=p1.py).order_by('id')[sjs:sjs + 4]
            sjzq = random.randint(1, 4)
            p1.zq = sjzq
    except xhzd_surnfu.DoesNotExist:
        raise Http404("Poll does not exist")
    return render(request,'testMiddleLibrary.html', {'zd': p})

@auth
def testResult(request):
    try:
        currUser = request.session.get('username','')
        #print("currUser0"+currUser)
        p1 = testResult_surnfu.objects.filter(testType="junior",creater__username=currUser).order_by('beginTime')[:5]
        junCodeList = []  ##成绩
        junTimeList = []  ##测试时间，单位秒
        junPassNum = 0  ##合格次数
        for p in p1:
            junCodeList.append(int(p.result))
            time1 = math.ceil((int(p.endTime) - int(p.beginTime)) / 1000)
            junTimeList.append(time1)
            if int(p.result) >= 60:
                junPassNum = junPassNum + 1

        p2 = testResult_surnfu.objects.filter(testType="middle",creater__username=currUser).order_by('beginTime')[:5]
        midCodeList = []  ##成绩
        midTimeList = []  ##测试时间，单位秒
        midPassNum = 0  ##合格次数
        for p in p2:
            midCodeList.append(int(p.result))
            time2 = math.ceil((int(p.endTime) - int(p.beginTime)) / 1000)
            midTimeList.append(time2)
            if int(p.result) >= 60:
                midPassNum = midPassNum + 1

        p3 = testResult_surnfu.objects.filter(testType="high",creater__username=currUser).order_by('beginTime')[:5]
        highCodeList = []  ##成绩
        highTimeList = []  ##测试时间，单位秒
        highPassNum = 0  ##合格次数
        for p in p3:
            highCodeList.append(int(p.result))
            time3 = math.ceil((int(p.endTime) - int(p.beginTime)) / 1000)
            highTimeList.append(time3)
            if int(p.result) >= 60:
                highPassNum = highPassNum + 1

    except testResult_surnfu.DoesNotExist:
        raise Http404("Poll does not exist")
    return render(request, 'testResult.html',
                  {'junCodeList': junCodeList, 'junTimeList': junTimeList, 'junPassNum': junPassNum,
                   'midCodeList': midCodeList, 'midTimeList': midTimeList, 'midPassNum': midPassNum,
                   'highCodeList': highCodeList, 'highTimeList': highTimeList, 'highPassNum': highPassNum})

@auth
def index(request):
    try:
        currUser = request.session.get('username','')
        #print("currUser0"+currUser)
        p1 = testResult_surnfu.objects.filter(testType="junior",creater__username=currUser).order_by('beginTime')[:5]
        junCodeList = []  ##成绩
        junTimeList = []  ##测试时间，单位秒
        junPassNum = 0  ##合格次数
        for p in p1:
            junCodeList.append(int(p.result))
            time1 = math.ceil((int(p.endTime) - int(p.beginTime)) / 1000)
            junTimeList.append(time1)
            if int(p.result) >= 60:
                junPassNum = junPassNum + 1

        p2 = testResult_surnfu.objects.filter(testType="middle",creater__username=currUser).order_by('beginTime')[:5]
        midCodeList = []  ##成绩
        midTimeList = []  ##测试时间，单位秒
        midPassNum = 0  ##合格次数
        for p in p2:
            midCodeList.append(int(p.result))
            time2 = math.ceil((int(p.endTime) - int(p.beginTime)) / 1000)
            midTimeList.append(time2)
            if int(p.result) >= 60:
                midPassNum = midPassNum + 1

        p3 = testResult_surnfu.objects.filter(testType="high",creater__username=currUser).order_by('beginTime')[:5]
        highCodeList = []  ##成绩
        highTimeList = []  ##测试时间，单位秒
        highPassNum = 0  ##合格次数
        for p in p3:
            highCodeList.append(int(p.result))
            time3 = math.ceil((int(p.endTime) - int(p.beginTime)) / 1000)
            highTimeList.append(time3)
            if int(p.result) >= 60:
                highPassNum = highPassNum + 1
    except testResult_surnfu.DoesNotExist:
        raise Http404("Poll does not exist")
    statu = "登陆"
    name = ""
    return render(request, 'index.html', context={"statu": statu, "name": name,
                                                  'junCodeList': junCodeList, 'junTimeList': junTimeList,
                                                  'junPassNum': junPassNum,
                                                  'midCodeList': midCodeList, 'midTimeList': midTimeList,
                                                  'midPassNum': midPassNum,
                                                  'highCodeList': highCodeList, 'highTimeList': highTimeList,
                                                  'highPassNum': highPassNum
                                                  })


def login(request):
    error_msg=""
    if request.method == 'POST':
        user = request.POST.get('user',None)
        pswd = request.POST.get('psd',None)
        if(user == '' and pswd == ''):
            error_msg="请输入你的用户名或密码"
        try:
            p = User.objects.filter(username=user).order_by('id')
        except User.DoesNotExist:
            raise Http404("Poll does not exist")
        for p1 in p:
            if (check_password(pswd, p1.password)):
                error_msg = ""
                request.session['username'] = user
                request.session.set_expiry(600) #s失效时间，单位秒
                return redirect('/user/index',{"user":user, "pswd":pswd})
            else:
                error_msg = '用户名或者密码错误'
    return render(request,'login.html',{"error_msg":error_msg})


def logout(request):
    del request.session['username']
    return redirect('/user/login')

def transcipt(request):
    return render(request,'transcipt.html')



